	#include <stdlib.h>
	#include <stdio.h>
	#include <conio.h>
	#include <string.h>

void encode(const char buffer[3], const char *alphabet, char output[]) {
	const int len = strlen(output);

	if(buffer[0] == 0)
		return;

	output[len]		= alphabet[buffer[0] >> 2];
	output[len+1]	= alphabet[((buffer[0] & 3) << 4)  + (buffer[1] >> 4)];

	if(buffer[1] == 0) {
		output[len+2] = '=';
		output[len+3] = '\0';
		return;
	}
	output[len+2]	= alphabet[((buffer[1] & 15) << 2) + (buffer[2] >> 6)];

	if(buffer[2] == 0) {
		output[len+3] = '=';
		output[len+4] = '\0';
		return;
	}
	output[len+3]	= alphabet[buffer[2] & 63];
	output[len+4]	= '\0';
}

void decode(const char input[4], const char *alphabet, char output[]){
	int i, j;
	int indices[4];



	unsigned int buffer = 0;

	for(i = 0; i < 4; i++) {
		if(input[i] == '=')
			indices[i] = 0;
		else
			for(j = 0; j < (int)strlen(alphabet); j++) {
				if(input[i] == alphabet[j])
					indices[i] = j;
			}
	}

	buffer = (indices[0] << 18) + (indices[1] << 12) + (indices[2] << 6) + indices[3];

	output[0] = (buffer >> 16) & 0xFF;
	output[1] = (buffer >> 8) & 0xFF;
	output[2] = buffer & 0xFF;
}

void main(int count, const char *values[])
{
	const char* alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

	FILE* file_for_input;
	FILE* file_for_output;

	int i,j;
	int choice;
	int reading = 1;
	int regim;

	char buffer[3];
	char buff[4];
	char decoding_buffer[4];
	
	
	char* output = (char*) malloc(4*sizeof(char));

	if (count == 4)
	{
		if (strcmp(values[1], "-e") == 0)
			regim = 1;

		else if (strcmp(values[1], "-d") == 0)
			regim = 2;
		
	}
	else
	{
		printf("fail arguments,,, ERROR\n");
		return;
	}

	output[0] = '\0';
	
		file_for_input    = fopen(values[2], "r");
		file_for_output	  = fopen(values[3], "wb");

		if (file_for_input == NULL || file_for_output == NULL ){
			printf(" Fail %s or %s file\n", "file_for_write","file_for_read");
			return;
		}

	if (regim == 1){

		while (reading){
			for (i = 0; i < 3; i++){
				buffer[i] = fgetc(file_for_input);
				if(buffer[i] == EOF){
					for(j = i; j < 3; j++){
						buffer[j] = 0; 
					}
					reading = 0;
					break;
				}
			}
			encode(buffer, alphabet, output);
		}
		for(i = 0; i < 4; i++)
			fputc(output[i], file_for_output);
	}



	if (regim == 2){

		while (reading){
			for (i = 0; i < 4; i++){

				decoding_buffer[i] = fgetc(file_for_input);					
				if(decoding_buffer[i] == '\n')
					i--;					

				if(decoding_buffer[i] == EOF){
					reading = 0;
					break;
				}			
			}

			if(reading == 0)
				break;

			decode(decoding_buffer, alphabet, output);

			for (i = 0; i < 3; i++)
				fputc(output[i], file_for_output);		

		}							
	}


	printf("ok\n");

	fclose(file_for_input);
	fclose(file_for_output);

	system("pause");

	free(output);
}